package com.kert.utils;

import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.poi.ss.usermodel.WorkbookFactory.*;

public class ExcelUtil {
    public static ArrayList<Object> read(InputStream is) throws IOException {
        Workbook sheets = create(is);
        Sheet sheet = sheets.getSheetAt(0);
        ArrayList<Object> ret = new ArrayList<>();
        Row title = sheet.getRow(0);
        for (Row row:sheet){
            HashMap<Object, Object> rowMap = new HashMap<>();
            for(int i=0;i<row.getLastCellNum();i++){
                Cell cell = row.getCell(i);
                String cellVal="";
                if(cell!=null){
                    cellVal=cell.getStringCellValue();
                }
                rowMap.put(title.getCell(i).getStringCellValue(),cellVal);
            }
            ret.add(rowMap);
        }
        sheets.close();
        return ret;
    }

    public static void write(List<Map> dataList,String uri) throws IOException {
        // Create workbook and sheet
        Workbook workbook = create(true);
        Sheet sheet = workbook.createSheet();
        // Write data to sheet
        int rowNum = 0;
        for (Map<String, String> data : dataList) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for (String key : data.keySet()) {
                Cell cell = row.createCell(colNum++);
                cell.setCellValue(data.get(key));
            }
        }

        // Save workbook to file
        FileOutputStream outputStream = new FileOutputStream(uri);
        workbook.write(outputStream);
        workbook.close();
    }
}
